package com.lry.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

public class SegmentLock<T>{

    private Integer segments = 16;//默认分段数量

    private final Map<Integer,ReentrantLock> lockMap = new HashMap<>();

    public SegmentLock(){
        init(null, false);
    }

    public SegmentLock(Integer counts, boolean fair){
        init(counts, fair);
    }

    private void init(Integer counts, boolean fair){
        if (counts != null) {
            segments = counts;
        }
        for (int i = 0; i < segments; i++) {
            lockMap.put(i, new ReentrantLock(fair));
        }
    }

    public void lock(T key){
        int hash = key.hashCode()>0?key.hashCode():key.hashCode()+Integer.MAX_VALUE;
        ReentrantLock lock = lockMap.get(hash % segments);
        lock.lock();
    }

    public void unlock(T key){
        int hash = key.hashCode()>0?key.hashCode():key.hashCode()+Integer.MAX_VALUE;
        ReentrantLock lock = lockMap.get(hash % segments);
        lock.unlock();
    }


}